var http   = require("http");
var url    = require("url");
var config = require("../config/config");
var router = require("../config/router");

var MIME = {
	'json'  : 'application/json',
	'xml'   : 'text/xml',
	'html'  : 'text/html'
}

function start() {
	function onRequest(request, response) {
		var pathname = url.parse(request.url).pathname;
			console.log("Request for:" + pathname);
		    pathname = pathname.replace(/(^\/*)/g,"");

		var query = url.parse(request.url, true).query;
		console.log(query);
		// 根据请求后缀,确定返回头
		var type = query['type'];
		if (typeof MIME[query['type']] == 'undefined') {
			type = config['default_mime'];
		};
		global.type = type;
		response.writeHead(200, {"Content-Type": MIME[type] + "; charset=utf-8"});

		var content = '';
		if (typeof router[pathname] == 'function') {
			content = router[pathname](query);
			// 确保 router 返回值 不能是空类型
			content = content ? content : '';
		} else {
			console.log('[' + pathname + '] Request Is Not Exist');
			content = config['noreq'];
		}
		response.write(content);
		response.end();
	}

	var port = config['port'];
	http.createServer(onRequest).listen(port);
	console.log("Server has started at port " + port);
}

exports.start = start;